export class IframeCleaner {
  shouldKilled: boolean = false;
  messageListener: boolean = false;

  enable: boolean = false;

  constructor() {}

  public setEnable(status: boolean) {
    // _console.log(status, "set enable");
    this.enable = status;
    if (this.enable) {
      this.removeUselessIframe();
    }
  }

  private iframeListener() {
    if (this.messageListener) return;
    window.addEventListener("message", (data) => {
      //   _console.log(data, "message");
      switch (data.data.type) {
        case "confirmKill":
          document.querySelectorAll("iframe")[data.data.index].remove();
          this.removeUselessIframe();
          break;
        case "kill":
          if (this.shouldKilled) {
            window.parent.postMessage(
              { type: "confirmKill", index: data.data.index },
              "*"
            );
          }
          break;
        case "count":
          const ifrs = Array.from(document.querySelectorAll("iframe"));
          ifrs.forEach((val, index) => {
            val.contentWindow &&
              val.contentWindow.postMessage({ index, type: "kill" }, "*");
          });
          break;
      }
    });

    this.messageListener = true;
  }

  private removeUselessIframe() {
    this.iframeListener();

    if (window.self === window.top) return;

    const ifr = document.querySelectorAll("iframe");
    const vid = document.querySelectorAll("video");

    // console.log(this.enable, "enable");

    if (this.enable && ifr.length === 0 && vid.length === 0) {
      this.shouldKilled = true;
      window.parent.postMessage(
        {
          type: "count",
        },
        "*"
      );
    }
  }
}
